<template>
    <el-dialog title="spu编辑"   :visible.sync="isShowEditSpu" :close-on-click-modal="false">
         <el-form :model="spu" label-width="80px">
     <el-form-item label="标题">
        <el-input v-model="spu.title" autocomplete="off"></el-input>
     </el-form-item>
     <el-form-item label="副标题">
        <el-input v-model="spu.subtitle" autocomplete="off"></el-input>
     </el-form-item>
     <el-form-item label="价格">
        <el-input v-model="spu.price" autocomplete="off"></el-input>
     </el-form-item>
     <el-form-item label="折扣">
        <el-input v-model="spu.discountPrice" autocomplete="off"></el-input>
     </el-form-item>
     <el-form-item label="分类"> 
       <el-select v-model="spu.categoryId">
        <el-option
        v-for="item in category"
        :key="item.id"
        :label="item.name"
        :value="item.id">
       </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="是否上架">
    <el-switch
        v-model="spu.online"
        active-text="上架"
        inactive-text="下架">
    </el-switch>
    </el-form-item>
     <el-form-item label="主图">
        <el-upload
         class="avatar-uploader"
         :action="objdata.host"
         :show-file-list="false"
         :data="objdata"
         :on-success="handleAvatarSuccess"
         :before-upload="ossPolicy">
         <!-- 显示图片 -->
       <img v-if="imageUrl" :src="imageUrl" class="avatar">
       <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
     </el-form-item>
      <el-form-item label="轮播图">
       <el-upload
        :action="objdatalist.host"
        list-type="picture-card"
        :file-list="fileList"
        :data="objdatalist"
        :before-upload="ossPolicyList"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess02"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url" alt=""
            >
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
      <!-- 轮播图的图片显示 -->
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      </el-form-item>

      <el-form-item label="标签">
         <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
            </el-tag>
            <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue" 
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm" >            
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>        
      </el-form-item>

      <el-form-item label="选择规格">
        <el-select v-model="keyValue" multiple placeholder="请选择">
        <el-option
        v-for="item in spec"
        :key="item.id"
        :label="item.name"
        :value="item.id">
       </el-option>
     </el-select>
     </el-form-item>

     <el-form-item label="描述">
        <el-input v-model="spu.description" autocomplete="off"></el-input>
     </el-form-item>
   </el-form>
   <div slot="footer" class="dialog-footer">
      <el-button @click="updatSpu">确认</el-button>
      <el-button @click="()=>isShowEditSpu=false">取消</el-button>
   </div>
</el-dialog>
</template>

<script>


export default {
    props:['current'],
    data() {
        return {       
            objdata:{
              OSSAccessKeyId:'',
              policy:'',
              Signature:'',
              key:'',
              host:'',
              dir:''
            },
             objdatalist:{
              OSSAccessKeyId:'',
              policy:'',
              Signature:'',
              key:'',
              host:'',
              dir:'',
              // imgaddress:''
            },
            spu:{
             id:'',
             title:'',
             subtitle:'',
             price:'',
             discountPrice:'',
             description:'' ,
             categoryId:'',
             img: '',// 主图地址 
             online:'',
             tags:''                              
            },
   
            category:[{
                id:'',
                name:''
             }],
             specKeys:[{
               id: '',
               name: ''
             }],
             spuImgs:[], 
             dynamicTags:[],
             inputVisible: false,
             inputValue: '',
             imageUrl: '',// 主图的地址
             isShowEditSpu:false,
             value2:true,
            spec:[{
              id:'',
              name:'' 
            }],
             category:[{
                id:'',
                name:''
             }],
            keyValue:[],        
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            fileList:[],
            time:'',
            spuImg: [],//轮播图的url           
            imgList:[],
            imgs:[]
            
        }
    } ,
      methods:{
    async  updatSpu(){
      this.fileList = []
      // 这个也不用看
      if (this.spu.category === null) {
        this.spu.category = {}
      }
      // 获取规格
      this.spu.specKeys = this.spec.filter(s => {
        let flag = false
        this.keyValue.forEach(sp => {
          if (sp === s.id) {
            flag = true
            return
          }
        })
        return flag
      })
     
      // 标签
      this.spu.tags = this.dynamicTags.join('#')
      console.log(this.spu.tags)
      // 打印的是轮播图 你看下里面是什么 ，里面应该会有地址
      // console.log(this.spuImg);
      // 获取到轮播图
      this.spu.spuImgs = this.spu.spuImgs.map(i => {
        return { img: i.url }
      })
      //  console.log(this.spu.spuImgs)
     const editRes = await this.$http.put('/spu', this.spu)
      // console.log(editRes)
      if (editRes.data.code > 0) {
        this.$message({
          message: '数据修改成功',
          type: 'success'
        })
        this.$emit('refresh', this.current)
        this.isShowEditSpu = false
      }

         },

       updateSpu(id){
         this.$http.get(`/spu/${id}`)
         .then(res=>{
          // console.log(res);
          this.spu=res.data.data
          this.dynamicTags =res.data.data.tags.split('#')  
          this.specKeys = res.data.data.specKeys 
          this.spu = res.data.data
          this.keyValue = this.spu.specKeys.map(key => key.id)
          this.imageUrl = this.spu.img
          this.spu.images = this.spu.spuImgs.map(img => {
          const newImg = {
          id: img.id,
          url: img.img
        }
        return newImg
      })
      // 渲染轮播图
      this.fileList = [...this.spu.images]        
          })
      },
      getSpec(){
           this.$http.get("/spec/all")
           .then(res=>this.spec=res.data.data)
        },
        getCategory(){
            this.$http.get("/cate/all")
           .then(res=>this.category=res.data.data)
        },
    
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_=> {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      // 主图上传成功之后自动调用的成功回调函数
      handleAvatarSuccess(res, file) {
        // console.log(file.raw)
        this.imageUrl = URL.createObjectURL(file.raw);
        this.img = this.objdata.host + '/' + this.objdata.key
        // console.log(this.img)
      },
      handleAvatarSuccess02(res, file) {
      },
      // 图片删除
      handleRemove(file) {
        console.log(file);
        //,fileList
      this.spuImg = this.spuImg.filter(img => img.uid !== file.uid)
      this.fileList = this.spuImg
      console.log(this.fileList)// this.fileList用于图片删除
      console.log(this.spuImg)
      },
      // 轮播图的图片预览 
      handlePictureCardPreview(file) {
        console.log(file)
        this.dialogImageUrl = file.url;
        console.log(this.dialogImageUrl)
        this.dialogVisible = true;
      },
      handleDownload(file) {
        console.log(file);
      },
      // 
      getLastName(file) {
        return file.name.substr(file.name.indexOf('.'))
      },
      ossPolicy(file){
        // console.log(file.name);
              this.time = new Date().getTime() + this.getLastName(file)
              return new Promise((resolve,reject)=>{
               this.$http.get('/oss')
              .then(res=>{
                this.objdata.OSSAccessKeyId=res.data.accessid
                this.objdata.policy=res.data.policy
                this.objdata.Signature=res.data.signature
                this.objdata.key=res.data.dir + this.time
                this.objdata.host=res.data.host
                this.objdata.dir=res.data.dir
                resolve(true)
              })
              .catch(function (error){
                 console.log(error)
                 reject(false)
              })
           })       
      },
      ossPolicyList(file){
        this.time = new Date().getTime() + this.getLastName(file)
            return new Promise((resolve,reject)=>{
               this.$http.get('/oss')
              .then(res=>{
                this.objdatalist.OSSAccessKeyId=res.data.accessid
                this.objdatalist.policy=res.data.policy
                this.objdatalist.Signature=res.data.signature
                this.objdatalist.key=res.data.dir+ this.time
                this.objdatalist.host=res.data.host
                this.objdatalist.dir=res.data.dir
                this.spuImg.push({ uid: file.uid, url: this.objdatalist.host + '/' + this.objdatalist.key })
              
                resolve(true)
              })
              .catch(function (error){
                 console.log(error)
                 reject(false)
              })
           })       
      }    
    },

     mounted(){
       this.getSpec(),
       this.getCategory()
    }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
   
</style>